import asyncio
from typing import List
from bilibili_api.search import search_by_type, SearchObjectType
from bilibili_api.video import Video


class BilibiliScraper:
    async def search_videos(self, keywords: List[str], max_videos: int) -> List[str]:
        video_urls = []
        for keyword in keywords:
            search_result = await search_by_type(
                keyword=keyword, search_type=SearchObjectType.VIDEO
            )
            for item in search_result["result"]:
                if len(video_urls) >= max_videos:
                    break
                video_urls.append(item["arcurl"])
            if len(video_urls) >= max_videos:
                break
        return video_urls

    async def get_danmaku(self, video_url: str) -> List[str]:
        avid_str = video_url.split("/")[-1]
        if avid_str.startswith("av"):
            aid = int(avid_str[2:])
            video = Video(aid=aid)
            danmakus = await video.get_danmakus(0)
            return [d.text for d in danmakus]
        elif avid_str.startswith("BV"):
            video = Video(bvid=avid_str)
            danmakus = await video.get_danmakus(0)
            return [d.text for d in danmakus]
        return []